package com.blobfish.fiction.common.job;

import cn.hutool.core.util.NumberUtil;
import com.blobfish.fiction.book.BookChapterService;
import com.blobfish.fiction.book.service.impl.BookServiceImpl;
import com.blobfish.fiction.common.base.knowledge.DataDictKnowledge;
import com.blobfish.fiction.common.model.Book;
import com.blobfish.fiction.common.util.DownloadUtil;
import com.jfinal.aop.Aop;
import com.jfinal.log.Log;

import java.util.List;

/**
 * 检查数据库中小说最新章节定时任务
 * @author huangbo
 */
public class CheckLastestChaptersJob implements Runnable {
    private static final Log log = Log.getLog(CheckLastestChaptersJob.class);

    @Override
    public void run() {
        log.info("开始检查本地小说章节是否有更新");
        long startTime = System.currentTimeMillis();
        BookServiceImpl bookService = Aop.get(BookServiceImpl.class);
        BookChapterService bookChapterService = Aop.get(BookChapterService.class);
        //1. 获取状态为已下载的小说
        List<Book> bookList = bookService.listByState(DataDictKnowledge.BookStateEnum.DOWNLOADED.getDataCode());
        //2. 开始检查本地小说需不需要更新
        bookList.forEach(book -> {
            String bookNo = book.getBookNo();
            // 2.1 根据小说编号获取本地最新章节
            Long lastestChapterNum = bookChapterService.getLastestChapterNumByBookNo(bookNo);
            // 2.2 获取网上小说最新章节
            Long lastestChapterNumOfWeb = bookService.getLastestChapterNumOfWebByBookNo(bookNo);
            // 2.3 开始比较
            if (NumberUtil.compare(lastestChapterNum, lastestChapterNumOfWeb) == 0) {
                // 2.3.1 如果本地最新章节和网上的一致，则跳过
                return;
            } else {
                // 2.3.2.1 删除本地对应的txt文件
                bookService.dropTxtByBookNo(bookNo);
                // 2.3.2.2 将本地book状态改成有更新
                book.setState(DataDictKnowledge.BookStateEnum.CHANGED.getDataCode());
                book.update();
                // 2.3.2.3 添加到下载列表中去
                DownloadUtil.getInstance().addTask(bookNo);
            }
            log.info("检查本地小说章节是否有更新完毕，耗时:" + (System.currentTimeMillis() - startTime) + "ms");
        });

    }
}
